﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using Maticsoft.Common;
using System.Data;
using System.Text.RegularExpressions;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;


namespace Admin.Shop.Code
{
    public class Common
    {
        const string KEY_64 = "!@#1G^&*";  //密钥，注意了，是8个字符，64位
        const string IV_64 = "!@#1G^&*";

        //解密
        public static string Encode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
        }

        //加密
        public static string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }


        /// <summary>
        /// 获取指定位数的数字组成的随机字符串
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string GetRandomNum(int size)
        {
            string st = "";
            string chars = "123456789";
            int lan = chars.Length;
            Random rd = new Random();
            for (int i = 1; i <= size; i++)
            {
                int t = rd.Next(1, lan);
                st += chars.Substring(t, 1);
            }
            string str = st;
            return str;
        }

        /// <summary>
        /// 脚本过滤
        /// </summary>
        /// <param name="html">字符串</param>
        /// <returns>过滤后的字符串</returns>
        public static string wipeScript(string html)
        {
            Regex regex1 = new Regex(@"<script[\s\S]+</script *>", RegexOptions.IgnoreCase);
            Regex regex2 = new Regex(@" href *= *[\s\S]*script *:", RegexOptions.IgnoreCase);
            Regex regex3 = new Regex(@" on[\s\S]*=", RegexOptions.IgnoreCase);
            Regex regex4 = new Regex(@"<iframe[\s\S]+</iframe *>", RegexOptions.IgnoreCase);
            Regex regex5 = new Regex(@"<frameset[\s\S]+</frameset *>", RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
            html = regex4.Replace(html, ""); //过滤iframe
            html = regex5.Replace(html, ""); //过滤frameset
            return html;
        }

        /// <summary>
        /// 以时间重命名
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string ReNameByTime(string fileName)
        {
            int index = fileName.LastIndexOf(".");
            string lastName = fileName.Substring(index, fileName.Length - index);
            //新文件名称,以时间年月日时分秒作为文件名
            string newfile = DateTime.Now.ToString("yyMMddHHmmssfff") + lastName;
            return newfile;
        }

        public static string FileUploadImage(byte[] byteFileStream, string path, string imageFileName, string imagePathCode, bool isCompress)
        {
            string newFileName = ReNameByTime(imageFileName);
            string absoluteImagePath = path; //获取图片存放路径
            if (string.IsNullOrEmpty(absoluteImagePath))
                return "error";

            if (!isCompress)//不压缩图片
            {
                try
                {
                    string filePath = absoluteImagePath + imagePathCode + "/" + newFileName;
                    FileStream fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(byteFileStream);
                    bw.Flush();
                    fs.Close();
                    return newFileName;
                }
                catch (Exception ex)
                {
                    return "error";
                }
            }
            else//压缩图片
            {
                try
                {

                    string filePath = absoluteImagePath + imagePathCode + "/ori/" + newFileName;
                    //保持源图片
                    FileStream fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(byteFileStream);
                    bw.Flush();
                    fs.Close();

                    string newPath = absoluteImagePath + imagePathCode + "/middle/" + newFileName;
                    GetPicThumbnail(filePath, newPath, 500, 720, 100);

                    return newFileName;
                }
                catch (Exception ex)
                {
                    return "error";
                }
            }
        }


        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth"></param>
        /// <param name="flag">压缩质量 1-100</param>
        /// <returns></returns>
        public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
        {

            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);

            if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
            {
                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }
            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);
            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }

        }

    }
}